﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Visio.ForwardEngineer.DataModel;
using System.IO;
using Visio.ForwardEngineer.Properties;

namespace Visio.ForwardEngineer.UserInterface
{
    public partial class ForwardEngineerForm : Form
    {
        #region Properties
        /// <summary>
        ///     Returns the model file name chosen by the user
        /// </summary>
        public string ModelFileName
        {
            get
            {
                return comboBoxModelNames.SelectedItem.ToString();
            }
        }

        /// <summary>
        ///     Returns the output file name for the SQL generated script
        /// </summary>
        public string OutputFileName
        {
            get
            {
                return textBoxOutputFileName.Text;
            }
        }

        /// <summary>
        ///     Returns the database name chosen by the user
        /// </summary>
        public string DatabaseName
        {
            get
            {
                return textBoxDatabaseName.Text;
            }
        }

        /// <summary>
        ///     Returns a boolean indicating whether the user wants to generate the DROP database
        /// </summary>
        public bool GenerateDropDatabase
        {
            get
            {
                return checkBoxGenerateDropDatabase.Checked;
            }
        }

        /// <summary>
        ///     Returns a boolean indicating whether the user wants to generate the CREATE Database
        /// </summary>
        public bool GenerateCreateDatabase
        {
            get
            {
                return checkBoxGenerateCreateDatabase.Checked;
            }
        }

        /// <summary>
        ///     Returns a boolean indicating whether the user wants to open the generated 
        ///     SQL script after generation
        /// </summary>
        public bool OpenScript
        {
            get
            {
                return checkBoxOpenScript.Checked;
            }
        }

        /// <summary>
        ///     Returns a boolean indicating whether the user wants to add additional
        ///     code to thet script
        /// </summary>
        public bool AppendAdditionalCode
        {
            get
            {
                return checkBoxAppendCode.Checked;
            }
        }

        /// <summary>
        ///     Returns the name of the file with additional code
        /// </summary>
        public string AppendAdditionalCodeFileName
        {
            get
            {
                return textBoxAppendCode.Text;
            }
        }

        public bool UseTransactions
        {
            get { return chkTransactions.Checked; }
        }

        /// <summary>
        ///     Returns a boolean indicating whether the user wants 
        ///     generate for specific tables
        /// </summary>
        public bool SpecificTables
        {
            get { return checkBoxSpecifiedTables.Checked; }
        }

        /// <summary>
        ///     Get all specified tables
        /// </summary>
        private List<string> _SpecifiedTablesSelected = new List<string>();
        public List<string> SpecifiedTablesSelected
        {
            get
            {
                foreach (var item in checkedListBoxSpecifiedTables.CheckedItems)
                {
                    _SpecifiedTablesSelected.Add(item.ToString());
                }

                return _SpecifiedTablesSelected;
            }
        }

        #endregion

        /// <summary>
        /// Constructor for the form
        /// </summary>
        public ForwardEngineerForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// During form load we get the list of all the available models
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ForwardEngineerForm_Load(object sender, EventArgs e)
        {
            this.Icon = Resources.Folder_Applications_48x481;

            comboBoxModelNames.Items.Clear();
            string[] modelNames = ModelTransformer.GetModels();
            comboBoxModelNames.Items.AddRange(modelNames);
            if (modelNames.Length == 1)
            {
                comboBoxModelNames.SelectedItem = modelNames[0];
                comboBoxModelNames.Enabled = false;
            }
        }

        /// <summary>
        /// When the user changes the model, we update other
        /// options accordingly
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxModelNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            string modelFileName = comboBoxModelNames.SelectedItem.ToString();
            FileInfo modelFile = new FileInfo(modelFileName);
            string modelName = modelFile.Name.Substring(0, modelFile.Name.Length - modelFile.Extension.Length);
            textBoxDatabaseName.Text = modelName;
            textBoxOutputFileName.Text = modelFile.DirectoryName + "\\" + modelName + ".SQL";
            textBoxAppendCode.Text = modelFile.DirectoryName + "\\" + modelName + " SQL Code.SQL";
        }

        /// <summary>
        /// When the user changes the text of the "Append Code" box we verify whether the file
        /// exists or not and update the checkbox accordingly
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxAppendCode_TextChanged(object sender, EventArgs e)
        {
            if (File.Exists(textBoxAppendCode.Text))
            {
                checkBoxAppendCode.Checked = true;
            }
            else
            {
                checkBoxAppendCode.Checked = false;
            }
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.AddExtension = true;
            saveFileDialog.DefaultExt = "sql";
            saveFileDialog.Filter = "SQL Files (*.sql)|*.sql";
            saveFileDialog.Title = "Save file as";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxOutputFileName.Text = saveFileDialog.FileName;
            }
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {

        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.CheckFileExists = true;
            openFileDialog.CheckPathExists = true;
            openFileDialog.Multiselect = false;
            openFileDialog.Title = "Choose file to append...";
            openFileDialog.Filter = "SQL server files (*.sql)|*.sql|Text files (*.txt)|*.txt|All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxAppendCode.Text = openFileDialog.FileName;
            }
        }

        private void checkBoxAppendCode_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxAppendCode.Checked)
            {
                textBoxAppendCode.Enabled = true;
                btnOpen.Enabled = true;
            }
            else
            {
                textBoxAppendCode.Enabled = false;
                btnOpen.Enabled = false;
            }
        }

        private void checkBoxSpecifiedTables_CheckedChanged(object sender, EventArgs e)
        {
            checkedListBoxSpecifiedTables.Items.Clear();

            if (checkBoxSpecifiedTables.Checked)
            {
                checkedListBoxSpecifiedTables.Visible = true;
                ModelTransformer.ValidateModelStructure(this.ModelFileName);
                ModelStructure dataModel = ModelTransformer.GetModelStructure(this.ModelFileName);

                foreach (TableStructure table in dataModel.Tables.Values.OrderBy(p => p.QualifiedName))
                {
                    checkedListBoxSpecifiedTables.Items.Add(table.QualifiedName);
                }

            }
            else
            {
                checkedListBoxSpecifiedTables.Visible = false;
            }

        }
    }
}
